#include "graphicsview.h"
#include "testgl.h"

GraphicsView::GraphicsView(QWidget * parent,
                           bool already_tested,
                           int saved_max_size) : QWidget(parent)
{
this->setAttribute(Qt::WA_DeleteOnClose);
setupUi(this);
readSettings();

max_size = saved_max_size;

rotateSlider->addAction(actionReset_rotation);

scale = 250;
lcdNumber->addAction(actionReset_scale);
scene = new QGraphicsScene();

gl_tested = already_tested;
use_opengl = false;
QGLFormat f = QGLFormat::defaultFormat();
    if ( true == f.hasOpenGL() )
    {
    openGlButton->setDisabled(false);
    }
    else
    {
    openGlButton->setDisabled(true);
    }

view->setViewport( new QWidget );
view->setScene(scene);

connect( openGlButton,
         SIGNAL( toggled(bool) ),
         this,
         SLOT( toggleOpenGL() ) );
connect( closeToolButton,
         SIGNAL( clicked() ),
         this,
         SLOT( close() ) );
connect( rotateSlider,
         SIGNAL( valueChanged(int) ),
         this,
         SLOT( setMatrix() ) );
connect( zoomInButton,
         SIGNAL( clicked() ),
         this,
         SLOT( zoomIn() ) );
connect( zoomOutButton,
         SIGNAL( clicked() ),
         this,
         SLOT( zoomOut() ) );
connect( zoomInPButton,
         SIGNAL( clicked() ),
         this,
         SLOT( zoomInP() ) );
connect( zoomOutPButton,
         SIGNAL( clicked() ),
         this,
         SLOT( zoomOutP() ) );          
connect( actionReset_rotation,
         SIGNAL( triggered() ),
         this,
         SLOT( reset_rotation() ) );
connect( actionReset_scale,
         SIGNAL( triggered() ),
         this,
         SLOT( reset_scale() ) );          
}

GraphicsView::~GraphicsView()
{
delete scene;
}

void GraphicsView::closeEvent(QCloseEvent * e)
{
emit return_gl_tested(gl_tested, max_size);
writeSettings();
e->accept();
}

void GraphicsView::set_image(const QPixmap & pixmap)
{
    if (scene != NULL)
    {
    pixmap_item = scene->addPixmap( pixmap );
    pix_h = pixmap.height();
    pix_w = pixmap.width();
    }
}

void GraphicsView::toggleOpenGL()
{
    if ( true == openGlButton->isChecked() )
    {

    QGLFormat f = QGLFormat::defaultFormat();
    f.setSampleBuffers(true);
    //f.setStencil(true);
    f.setAlpha(true);
    f.setAlphaBufferSize(8);

        if ( true != gl_tested )
        {
        QString warn = tr("OpenGL renderer may improve performace.");
        warn.append( QLatin1String("\n") );
        warn.append( tr("It depends on operating system, graphic hardware and drivers.") );
        warn.append( QLatin1String("\n") );
        warn.append( tr("Access to graphic hardware can seldom crash the system") );
        warn.append( QLatin1String(" (") );
        warn.append( tr("in cases of brocken driver installation or hardware defect") );
        warn.append( QLatin1String(").") );
        warn.append( QLatin1String("\n") );
        warn.append( QLatin1String("\n") );
        warn.append( tr("Note: Autorepeat will be enabled on zoom buttons.") );
        warn.append( QLatin1String("\n    ") );
        warn.append( QLatin1String("\n    ") );
        warn.append( tr("Try OpenGL renderer?") );
        QMessageBox mBox;
        mBox.setWindowTitle( tr("Information") );
        mBox.setText( warn );
        mBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
            switch (mBox.exec())
            {
                case QMessageBox::No:
                openGlButton->setChecked(false);                
                return;
                break;
        
                default:
                break;
            } 
        TestGL * testGL = new TestGL( f );
        testGL->show();
        max_size = testGL->return_text_size();
        testGL->close();
        delete testGL;
        testGL = NULL;
        gl_tested = true;
        }
        
        if ( pix_h > max_size ||
             pix_w > max_size )
        {
        QString n = tr("Pixmap is too big.\n");
        n.append( tr("Maximum texture size for this hardware is ") );
        n.append( QString::number(max_size) );
        n.append( QLatin1String(" px.") );
        QMessageBox::information(this,
                                 "Information",
                                 n );
        openGlButton->setChecked(false);
        return;
        }
    use_opengl = true;
    zoomInButton->setAutoRepeat(true);
    zoomOutButton->setAutoRepeat(true);
    zoomInPButton->setAutoRepeat(true);
    zoomOutPButton->setAutoRepeat(true);
    
    QGLWidget * glwidget = new QGLWidget( f );
    view->setViewport( glwidget );
    }
    else
    {
    use_opengl = false;
    zoomInButton->setAutoRepeat(false);
    zoomOutButton->setAutoRepeat(false);
    zoomInPButton->setAutoRepeat(false);
    zoomOutPButton->setAutoRepeat(false);
    
    view->setViewport( new QWidget );
    }
}

void GraphicsView::setMatrix()
{
qreal scale_ = pow(2.0, (scale - 250) / 50.0);
lcdNumber->display(scale_);
QMatrix matrix;
matrix.scale(scale_, scale_);
matrix.rotate(rotateSlider->value() / 10.0);
view->setMatrix(matrix);
}

void GraphicsView::zoomIn()
{
    if (use_opengl)
    {
    scale += 1;
    }
    else
    {
    scale += 3;
    }
setMatrix();
}

void GraphicsView::zoomInP()
{
    if (use_opengl)
    {
    scale += 5;
    }
    else
    {
    scale += 15;
    }
setMatrix();
}

void GraphicsView::zoomOut()
{
    if (use_opengl)
    {
    scale -= 1;
    }
    else
    {
    scale -= 3;
    }
setMatrix();
}

void GraphicsView::zoomOutP()
{
    if (use_opengl)
    {
    scale -= 5;
    }
    else
    {
    scale -= 15;
    }
setMatrix();
}


void GraphicsView::reset_rotation()
{
rotateSlider->setValue(0);
}

void GraphicsView::reset_scale()
{
scale = 250;
setMatrix();
}

void GraphicsView::writeSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("GraphicsView") );
settings.setValue( QLatin1String("size"), QVariant( this->size() ) );
settings.setValue( QLatin1String("pos"), QVariant( this->pos() ) );
settings.endGroup();
}

void GraphicsView::readSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);                
settings.beginGroup( QLatin1String("GraphicsView") );
resize( settings.value( QLatin1String("size"), QSize( 750, 550 ) ).toSize() );
move( settings.value( QLatin1String("pos"), QPoint( 0, 0 ) ).toPoint() );
settings.endGroup();
}
